508D - Tanya and Password - CodeForces Solution


dfs and similar graphs *2500

Please click on ads to support us..

C++ Code:

/* In the name of Allah */
// Welcome to the Soldier Side!
// Where there's no one here, but me...
#include<bits/stdc++.h>
using namespace std;

const int N = 4e5 + 5;
vector<int> result;
vector<int> adj[N];
int n, m, d[N];
string t[N];

int get_id(string s) {
	static map<string, int> mp;
	return !mp.count(s)? t[m] = s, mp[s] = m++: mp[s];
}

void dfs(int u) {
	while (!adj[u].empty()) {
		int v = adj[u].back();
		adj[u].pop_back();
		dfs(v);
	}
	result.push_back(u);
}

void read_input() {
	cin >> n;
	for (int i = 0; i < n; i++) {
		string s;
		cin >> s;

		int u = get_id(s.substr(0, 2));
		int v = get_id(s.substr(1));
		adj[u].push_back(v);
		d[u]++, d[v]--;
	}
}

void solve() {
	int cnt = 0;
	for (int u = 0; u < n; u++)
		if (d[u])
			cnt++;
	if (cnt > 2) {
		cout << "NO";
		exit(0);
	}

	for (int u = 0; u < m; u++)
		if (d[u] > 0) {
			if (d[u] > 1) {
				cout << "NO";
				exit(0);
			}

			dfs(u);
			return;
		}
	dfs(0);
}

void write_output() {
	if (result.size() < n + 1) {
		cout << "NO";
		return;
	}

	reverse(result.begin(), result.end());
	cout << "YES\n" << t[result[0]][0];
	for (int p: result)
		cout << t[p][1];
}

int main() {
	ios:: sync_with_stdio(0), cin.tie(0), cout.tie(0);
	read_input(), solve(), write_output();
	return 0;
}


Comments

Submit
0 Comments
More Questions

402. Remove K Digits
97. Interleaving String
543. Diameter of Binary Tree
124. Binary Tree Maximum Path Sum
1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
501A - Contest
160A- Twins
752. Open the Lock
1535A - Fair Playoff
1538F - Interesting Function
1920. Build Array from Permutation
494. Target Sum
797. All Paths From Source to Target
1547B - Alphabetical Strings
1550A - Find The Array
118B - Present from Lena
27A - Next Test
785. Is Graph Bipartite
90. Subsets II
1560A - Dislike of Threes
36. Valid Sudoku
557. Reverse Words in a String III
566. Reshape the Matrix
167. Two Sum II - Input array is sorted
387. First Unique Character in a String
383. Ransom Note
242. Valid Anagram
141. Linked List Cycle
21. Merge Two Sorted Lists
203. Remove Linked List Elements